<script setup>
import { useRouter } from 'vue-router';
import { ref, computed } from 'vue';
import { showToast } from 'vant';
import { getCodeFn, checkedCodeFn } from '@/api/register';

const router = useRouter()
const code = ref('')
const buttonText = ref('发送验证码')
const codeButtonFlag = ref(false)

const flag = computed(() => {
    return code.value.length != 6
})

// 提交验证码
function onSubmit() {
    checkedCodeFn({
        code: code.value
    }).then(res => {
        // console.log(res);
        showToast(res.message);
        if (res.data.flag) {
            router.push('/register/step3')
        }
    })
}

// 获取验证码
function getCode() {
    getCodeFn().then(res => {
        if (res.code == '200') {
            console.log(res.data.code);
            showToast(res.data.code)
            codeButtonFlag.value = true
            let allTime = 60
            const time = setInterval(() => {
                if (allTime > 0) {
                    allTime--
                    buttonText.value = allTime + 's后获取'
                } else {
                    allTime = 60
                    codeButtonFlag.value = false
                    buttonText.value = '重新获取'
                    clearInterval(time)
                }
            }, 1000)
        } else {
            showToast(res.message)
        }

    })
}

function toback() {
    router.back()
}
</script>

<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="code" name="验证码" label="验证码" placeholder="请输入验证码"
                :rules="[{ required: true, message: '请填写验证码' }]">
                <template #button>
                    <van-button size="small" type="primary" @click="getCode" :disabled="codeButtonFlag">{{ buttonText
                        }}</van-button>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="danger" native-type="submit" :disabled="flag">
                下一步
            </van-button>
        </div>
    </van-form>
    <div style="margin: 16px;">
        <van-button round block type="success" native-type="submit" @click="toback">
            返回上一步
        </van-button>
    </div>
</template>